package com.example.note2;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.text.SimpleDateFormat;
import java.util.Date;

public class EditActivity extends BaseActivity {

    private EditText editText;
    private Toolbar myToolbar;
    private String old_content = "";
    private String old_time = "";
    private int old_Tag = 1; // 之前的标签
    private long id = 0; // 笔记 ID
    private int openMode = 0; // 打开模式
    private int tag = 1; // 默认标签
    public Intent intent = new Intent();
    private boolean tagChange = false; // 修改标签标志
    private String userId; // 当前用户ID

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_edit);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        editText = findViewById(R.id.et);
        myToolbar = findViewById(R.id.toolbar);
        Intent getIntent = getIntent(); // 获取传入的 Intent
        openMode = getIntent.getIntExtra("mode", 0); // 获取打开模式
        userId = getIntent.getStringExtra("user_id"); // 获取用户ID

        setSupportActionBar(myToolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        // Toolbar 返回键实现
        myToolbar.setNavigationOnClickListener(v -> {
            autoSetMessage();
            setResult(RESULT_OK, intent);
            finish();
        });

        // 如果是编辑已有的笔记
        if (openMode == 3) {
            // 获取传入的数据
            id = getIntent.getLongExtra("id", 0);
            old_content = getIntent.getStringExtra("content");
            old_time = getIntent.getStringExtra("time");
            old_Tag = getIntent.getIntExtra("tag", 1);
            // 编辑栏设置旧内容
            editText.setText(old_content);
            // 设置光标在最后面
            editText.setSelection(old_content.length());
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.edit_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == R.id.delete) {
            new AlertDialog.Builder(EditActivity.this)
                    .setMessage("确定删除吗？")
                    .setPositiveButton(android.R.string.yes, (dialog, which) -> {
                        if (openMode == 4) { // 新建笔记
                            intent.putExtra("mode", -1);
                            setResult(RESULT_OK, intent);
                        } else { // 删除已打开的笔记
                            intent.putExtra("mode", 2);
                            intent.putExtra("id", id);
                            setResult(RESULT_OK, intent);
                        }
                        finish();
                    })
                    .setNegativeButton(android.R.string.no, (dialog, which) -> dialog.dismiss())
                    .create()
                    .show();
        }
        return super.onOptionsItemSelected(item);
    }

    // 处理按键事件
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_HOME) {
            // do something
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_BACK) {
            autoSetMessage();
            setResult(RESULT_OK, intent);
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    // 自动设置消息
    private void autoSetMessage() {
        if (openMode == 4) { // 新建笔记
            if (editText.getText().toString().length() == 0) {
                intent.putExtra("mode", -1);
            } else { // 新建笔记
                intent.putExtra("mode", 0);
                intent.putExtra("content", editText.getText().toString());
                intent.putExtra("time", dateToStr());
                intent.putExtra("tag", tag);
                intent.putExtra("user_id", userId); // 传递用户ID
            }
        } else { // 打开已有笔记
            if (editText.getText().toString().equals(old_content) && !tagChange)
                intent.putExtra("mode", -1);
            else {
                intent.putExtra("mode", 1);
                intent.putExtra("content", editText.getText().toString());
                intent.putExtra("time", dateToStr());
                intent.putExtra("id", id); // 传出id修改
                intent.putExtra("tag", tag);
                intent.putExtra("user_id", userId); // 传递用户ID
            }
        }
    }

    // 将时间转换为字符串，格式为 yyyy-MM-dd HH:mm:ss
    public String dateToStr() {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return simpleDateFormat.format(date);
    }
}
